#pragma once

#include <cstdint>
#include <cstring>
#include <string>
#include <vector>

namespace hude
{
    namespace safe
    {
        /*********************************************************************
         * @brief SHA-1计算实现细节
         */
        namespace details_sha1
        {
            /* #define LITTLE_ENDIAN * This should be #define'd already, if true. */
            /* #define SHA1HANDSOFF * Copies data before messing with it. */

            struct ctx_t
            {
                uint32_t state[5];
                uint32_t count[2];
                unsigned char buffer[64];
            };

#           define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))

            /* blk0() and blk() perform the initial expand. */
            /* I got the idea of expanding during the round function from SSLeay */
#           if BYTE_ORDER == LITTLE_ENDIAN
#               define blk0(i) (block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF))
#           elif BYTE_ORDER == BIG_ENDIAN
#               define blk0(i) block->l[i]
#           else
#               error "Endianness not defined!"
#           endif

#           define blk(i) (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ block->l[(i + 2) & 15] ^ block->l[i & 15], 1))

            /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#           define R0(v, w, x, y, z, i)                                     \
                z += ((w & (x ^ y)) ^ y) + blk0(i) + 0x5A827999 + rol(v, 5); \
                w = rol(w, 30);
#           define R1(v, w, x, y, z, i)                                    \
                z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
                w = rol(w, 30);
#           define R2(v, w, x, y, z, i)                            \
                z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
                w = rol(w, 30);
#           define R3(v, w, x, y, z, i)                                          \
                z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
                w = rol(w, 30);
#           define R4(v, w, x, y, z, i)                            \
                z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
                w = rol(w, 30);

            struct sha1_t
            {
                enum : std::size_t { emRESULT_SIZE = 20U };

                /* Hash a single 512-bit block. This is the core of the algorithm. */
                static void transform( uint32_t state[5], const unsigned char buffer[64])
                {
                    uint32_t a, b, c, d, e;

                    typedef union
                    {
                        unsigned char c[64];
                        uint32_t l[16];
                    } CHAR64LONG16;

                    CHAR64LONG16 block[1]; /* use array to appear as a pointer */

                    memcpy(block, buffer, 64);

                    /* Copy context->state[] to working vars */
                    a = state[0];
                    b = state[1];
                    c = state[2];
                    d = state[3];
                    e = state[4];
                    /* 4 rounds of 20 operations each. Loop unrolled. */
                    R0(a, b, c, d, e, 0);
                    R0(e, a, b, c, d, 1);
                    R0(d, e, a, b, c, 2);
                    R0(c, d, e, a, b, 3);
                    R0(b, c, d, e, a, 4);
                    R0(a, b, c, d, e, 5);
                    R0(e, a, b, c, d, 6);
                    R0(d, e, a, b, c, 7);
                    R0(c, d, e, a, b, 8);
                    R0(b, c, d, e, a, 9);
                    R0(a, b, c, d, e, 10);
                    R0(e, a, b, c, d, 11);
                    R0(d, e, a, b, c, 12);
                    R0(c, d, e, a, b, 13);
                    R0(b, c, d, e, a, 14);
                    R0(a, b, c, d, e, 15);
                    R1(e, a, b, c, d, 16);
                    R1(d, e, a, b, c, 17);
                    R1(c, d, e, a, b, 18);
                    R1(b, c, d, e, a, 19);
                    R2(a, b, c, d, e, 20);
                    R2(e, a, b, c, d, 21);
                    R2(d, e, a, b, c, 22);
                    R2(c, d, e, a, b, 23);
                    R2(b, c, d, e, a, 24);
                    R2(a, b, c, d, e, 25);
                    R2(e, a, b, c, d, 26);
                    R2(d, e, a, b, c, 27);
                    R2(c, d, e, a, b, 28);
                    R2(b, c, d, e, a, 29);
                    R2(a, b, c, d, e, 30);
                    R2(e, a, b, c, d, 31);
                    R2(d, e, a, b, c, 32);
                    R2(c, d, e, a, b, 33);
                    R2(b, c, d, e, a, 34);
                    R2(a, b, c, d, e, 35);
                    R2(e, a, b, c, d, 36);
                    R2(d, e, a, b, c, 37);
                    R2(c, d, e, a, b, 38);
                    R2(b, c, d, e, a, 39);
                    R3(a, b, c, d, e, 40);
                    R3(e, a, b, c, d, 41);
                    R3(d, e, a, b, c, 42);
                    R3(c, d, e, a, b, 43);
                    R3(b, c, d, e, a, 44);
                    R3(a, b, c, d, e, 45);
                    R3(e, a, b, c, d, 46);
                    R3(d, e, a, b, c, 47);
                    R3(c, d, e, a, b, 48);
                    R3(b, c, d, e, a, 49);
                    R3(a, b, c, d, e, 50);
                    R3(e, a, b, c, d, 51);
                    R3(d, e, a, b, c, 52);
                    R3(c, d, e, a, b, 53);
                    R3(b, c, d, e, a, 54);
                    R3(a, b, c, d, e, 55);
                    R3(e, a, b, c, d, 56);
                    R3(d, e, a, b, c, 57);
                    R3(c, d, e, a, b, 58);
                    R3(b, c, d, e, a, 59);
                    R4(a, b, c, d, e, 60);
                    R4(e, a, b, c, d, 61);
                    R4(d, e, a, b, c, 62);
                    R4(c, d, e, a, b, 63);
                    R4(b, c, d, e, a, 64);
                    R4(a, b, c, d, e, 65);
                    R4(e, a, b, c, d, 66);
                    R4(d, e, a, b, c, 67);
                    R4(c, d, e, a, b, 68);
                    R4(b, c, d, e, a, 69);
                    R4(a, b, c, d, e, 70);
                    R4(e, a, b, c, d, 71);
                    R4(d, e, a, b, c, 72);
                    R4(c, d, e, a, b, 73);
                    R4(b, c, d, e, a, 74);
                    R4(a, b, c, d, e, 75);
                    R4(e, a, b, c, d, 76);
                    R4(d, e, a, b, c, 77);
                    R4(c, d, e, a, b, 78);
                    R4(b, c, d, e, a, 79);
                    /* Add the working vars back into context.state[] */
                    state[0] += a;
                    state[1] += b;
                    state[2] += c;
                    state[3] += d;
                    state[4] += e;
                    /* Wipe variables */
                    a = b = c = d = e = 0;

                    memset(block, '\0', sizeof(block));
                }

                /* SHA1Init - Initialize new context */
                static void init( ctx_t *context)
                {
                    /* SHA1 initialization constants */
                    context->state[0] = 0x67452301;
                    context->state[1] = 0xEFCDAB89;
                    context->state[2] = 0x98BADCFE;
                    context->state[3] = 0x10325476;
                    context->state[4] = 0xC3D2E1F0;
                    context->count[0] = context->count[1] = 0;
                }

                /* Run your data through this. */

                static void update( ctx_t *context, const unsigned char *data, uint32_t len)
                {
                    uint32_t i;

                    uint32_t j;

                    j = context->count[0];
                    if ((context->count[0] += len << 3) < j)
                        context->count[1]++;
                    context->count[1] += (len >> 29);
                    j = (j >> 3) & 63;
                    if ((j + len) > 63)
                    {
                        memcpy(&context->buffer[j], data, (i = 64 - j));
                        transform(context->state, context->buffer);
                        for (; i + 63 < len; i += 64)
                        {
                            transform(context->state, &data[i]);
                        }
                        j = 0;
                    }
                    else
                        i = 0;
                    memcpy(&context->buffer[j], &data[i], len - i);
                }

                /* Add padding and return the message digest. */

                static void final( ctx_t*context, unsigned char* out )
                {
                    unsigned int i;

                    unsigned char finalcount[8];

                    unsigned char c;

                    for (i = 0; i < 8; i++)
                    {
                        finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */
                    }

                    c = 0200;
                    update(context, &c, 1);
                    while ((context->count[0] & 504) != 448)
                    {
                        c = 0000;
                        update(context, &c, 1);
                    }
                    update(context, finalcount, 8); /* Should cause a SHA1Transform() */
                    for (i = 0; i < 20; i++)
                    {
                        out[i] = (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
                    }
                    /* Wipe variables */
                    memset(context, '\0', sizeof(*context));
                    memset(&finalcount, '\0', sizeof(finalcount));
                }
            };
        } //namespace details_sha1

        /*********************************************************************
         * @brief SHA-256计算实现细节
         */
        namespace details_sha256
        {
            static const uint32_t K[64] = {
                0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
                0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
                0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
                0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
                0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
                0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
                0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
                0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
                0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
                0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
                0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
                0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
                0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
                0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
                0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
                0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
            };

            struct ctx_t
            {
                uint8_t buf[64];
                uint32_t hash[8];
                uint32_t bits[2];
                uint32_t len;
            };

            struct sha256_t
            {
                enum : std::size_t { emRESULT_SIZE = 32U };

                /* -------------------------------------------------------------------------- */
                static inline uint8_t _shb(uint32_t x, uint32_t n)
                {
                    return ( (x >> (n & 31)) & 0xff );
                } /* _shb */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _shw(uint32_t x, uint32_t n)
                {
                    return ( (x << (n & 31)) & 0xffffffff );
                } /* _shw */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _r(uint32_t x, uint8_t n)
                {
                    return ( (x >> n) | _shw(x, 32 - n) );
                } /* _r */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _Ch(uint32_t x, uint32_t y, uint32_t z)
                {
                    return ( (x & y) ^ ((~x) & z) );
                } /* _Ch */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _Ma(uint32_t x, uint32_t y, uint32_t z)
                {
                    return ( (x & y) ^ (x & z) ^ (y & z) );
                } /* _Ma */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _S0(uint32_t x)
                {
                    return ( _r(x, 2) ^ _r(x, 13) ^ _r(x, 22) );
                } /* _S0 */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _S1(uint32_t x)
                {
                    return ( _r(x, 6) ^ _r(x, 11) ^ _r(x, 25) );
                } /* _S1 */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _G0(uint32_t x)
                {
                    return ( _r(x, 7) ^ _r(x, 18) ^ (x >> 3) );
                } /* _G0 */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _G1(uint32_t x)
                {
                    return ( _r(x, 17) ^ _r(x, 19) ^ (x >> 10) );
                } /* _G1 */

                /* -------------------------------------------------------------------------- */
                static inline uint32_t _word(uint8_t *c)
                {
                    return ( _shw(c[0], 24) | _shw(c[1], 16) | _shw(c[2], 8) | (c[3]) );
                } /* _word */

                /* -------------------------------------------------------------------------- */
                static inline void  _addbits(ctx_t *ctx, uint32_t n)
                {
                    if ( ctx->bits[0] > (0xffffffff - n) )
                        ctx->bits[1] = (ctx->bits[1] + 1) & 0xFFFFFFFF;
                    ctx->bits[0] = (ctx->bits[0] + n) & 0xFFFFFFFF;
                } /* _addbits */

                /* -------------------------------------------------------------------------- */
                static void _hash(ctx_t *ctx)
                {
                    uint32_t a, b, c, d, e, f, g, h, i;
                    uint32_t t[2];
                    uint32_t W[64];

                    a = ctx->hash[0];
                    b = ctx->hash[1];
                    c = ctx->hash[2];
                    d = ctx->hash[3];
                    e = ctx->hash[4];
                    f = ctx->hash[5];
                    g = ctx->hash[6];
                    h = ctx->hash[7];

                    for (i = 0; i < 64; i++) {
                        if ( i < 16 )
                            W[i] = _word(&ctx->buf[_shw(i, 2)]);
                        else
                            W[i] = _G1(W[i - 2]) + W[i - 7] + _G0(W[i - 15]) + W[i - 16];

                        t[0] = h + _S1(e) + _Ch(e, f, g) + K[i] + W[i];
                        t[1] = _S0(a) + _Ma(a, b, c);
                        h = g;
                        g = f;
                        f = e;
                        e = d + t[0];
                        d = c;
                        c = b;
                        b = a;
                        a = t[0] + t[1];
                    }

                    ctx->hash[0] += a;
                    ctx->hash[1] += b;
                    ctx->hash[2] += c;
                    ctx->hash[3] += d;
                    ctx->hash[4] += e;
                    ctx->hash[5] += f;
                    ctx->hash[6] += g;
                    ctx->hash[7] += h;
                } /* _hash */

                /* -------------------------------------------------------------------------- */
                static void init(ctx_t *ctx)
                {
                    if ( ctx != NULL ) {
                        ctx->bits[0]  = ctx->bits[1] = 0;
                        ctx->len      = 0;
                        ctx->hash[0] = 0x6a09e667;
                        ctx->hash[1] = 0xbb67ae85;
                        ctx->hash[2] = 0x3c6ef372;
                        ctx->hash[3] = 0xa54ff53a;
                        ctx->hash[4] = 0x510e527f;
                        ctx->hash[5] = 0x9b05688c;
                        ctx->hash[6] = 0x1f83d9ab;
                        ctx->hash[7] = 0x5be0cd19;
                    }
                } /* sha256_init */

                /* -------------------------------------------------------------------------- */
                static void update(ctx_t *ctx, const void *data, size_t len)
                {
                    size_t i;
                    const uint8_t *bytes = (const uint8_t *)data;

                    if ( (ctx != NULL) && (bytes != NULL) )
                        for (i = 0; i < len; i++) {
                            ctx->buf[ctx->len] = bytes[i];
                            ctx->len++;
                            if (ctx->len == sizeof(ctx->buf) ) {
                                _hash(ctx);
                                _addbits(ctx, sizeof(ctx->buf) * 8);
                                ctx->len = 0;
                            }
                        }
                } /* sha256_hash */

                /* -------------------------------------------------------------------------- */
                static void final(ctx_t *ctx, uint8_t *hash)
                {
                    uint32_t i, j;

                    if ( ctx != NULL ) {
                        j = ctx->len % sizeof(ctx->buf);
                        ctx->buf[j] = 0x80;
                        for (i = j + 1; i < sizeof(ctx->buf); i++)
                            ctx->buf[i] = 0x00;

                        if ( ctx->len > 55 ) {
                            _hash(ctx);
                            for (j = 0; j < sizeof(ctx->buf); j++)
                                ctx->buf[j] = 0x00;
                        }

                        _addbits(ctx, ctx->len * 8);
                        ctx->buf[63] = _shb(ctx->bits[0],  0);
                        ctx->buf[62] = _shb(ctx->bits[0],  8);
                        ctx->buf[61] = _shb(ctx->bits[0], 16);
                        ctx->buf[60] = _shb(ctx->bits[0], 24);
                        ctx->buf[59] = _shb(ctx->bits[1],  0);
                        ctx->buf[58] = _shb(ctx->bits[1],  8);
                        ctx->buf[57] = _shb(ctx->bits[1], 16);
                        ctx->buf[56] = _shb(ctx->bits[1], 24);
                        _hash(ctx);

                        if ( hash != NULL )
                            for (i = 0, j = 24; i < 4; i++, j -= 8) {
                                hash[i     ] = _shb(ctx->hash[0], j);
                                hash[i +  4] = _shb(ctx->hash[1], j);
                                hash[i +  8] = _shb(ctx->hash[2], j);
                                hash[i + 12] = _shb(ctx->hash[3], j);
                                hash[i + 16] = _shb(ctx->hash[4], j);
                                hash[i + 20] = _shb(ctx->hash[5], j);
                                hash[i + 24] = _shb(ctx->hash[6], j);
                                hash[i + 28] = _shb(ctx->hash[7], j);
                            }
                    }
                } /* sha256_done */
            };

        } //namespace details_sha256

        /*********************************************************************
         * @brief SHA-X计算实现细节
         */
        template< int N >
        struct _sha_t {};

        template<>
        struct _sha_t< 1 >
        {
            typedef details_sha1::ctx_t ctx_t;
            typedef details_sha1::sha1_t operator_t;
        };

        template<>
        struct _sha_t< 256 >
        {
            typedef details_sha256::ctx_t ctx_t;
            typedef details_sha256::sha256_t operator_t;
        };

        /*********************************************************************
         * @brief SHA-X计算实现细节
         */
        template< int N >
        struct sha_t
        {
            enum : int { emSHA = N };

            typedef typename _sha_t< N >::ctx_t ctx_t;
            typedef typename _sha_t< N >::operator_t opt_t;
            typedef sha_t< N > this_t;

            /*********************************************************************
             * @brief 实例的算法上下文
             */
            ctx_t ctx;

            /*********************************************************************
             * @brief 实例构造及初始化
             */
            sha_t()
            {
                opt_t::init( &ctx );
            }

            /*********************************************************************
             * @brief 加入计算内容
             * @param  dat: 输入内容
             * @param  siz: 输入长度
             * @return 返回对象实例自身，方便链式操作
             */
            this_t& update( const uint8_t* dat, std::size_t siz )
            {
                opt_t::update( &ctx, dat, siz );
                return *this;
            }

            /*********************************************************************
             * @brief 加入计算内容
             * @param  dat: 输入内容
             * @param  siz: 输入长度
             * @return 返回对象实例自身，方便链式操作
             */
            this_t& update( const std::string& dat, std::size_t siz = 0U )
            {
                opt_t::update( &ctx, (const uint8_t*)&(dat[0]), siz? siz : dat.size() );
                return *this;
            }

            /*********************************************************************
             * @brief 加入计算内容
             * @param  dat: 输入内容
             * @param  siz: 输入长度
             * @return 返回对象实例自身，方便链式操作
             */
            this_t& update( const std::vector< uint8_t >& dat, std::size_t siz = 0U )
            {
                opt_t::update( &ctx, (const uint8_t*)&(dat[0]), siz? siz : dat.size() );
                return *this;
            }

            /*********************************************************************
             * @brief 加入多个计算内容
             * @param  b: 输入内容的起始迭代器
             * @param  e: 输入内容的结束迭代器
             * @return 返回对象实例自身，方便链式操作
             */
            template< typename _itr >
            this_t& update( _itr b, _itr e )
            {
                opt_t::update( &ctx, (const uint8_t*)&(*b), e - b );

                return *this;
            }

            /*********************************************************************
             * @brief 加入计算内容
             * @param  dat: 输入内容
             * @param  siz: 输入长度
             * @return 返回对象实例自身，方便链式操作
             */
            this_t& operator()( const uint8_t* dat, std::size_t siz )
            {
                opt_t::update( &ctx, dat, siz );
                return *this;
            }

            /*********************************************************************
             * @brief 加入计算内容
             * @param  dat: 输入内容
             * @param  siz: 输入长度
             * @return 返回对象实例自身，方便链式操作
             */
            this_t& operator()( const std::string& dat, std::size_t siz = 0U )
            {
                opt_t::update( &ctx, (const uint8_t*)&(dat[0]), siz? siz : dat.size() );
                return *this;
            }

            /*********************************************************************
             * @brief 加入计算内容
             * @param  dat: 输入内容
             * @param  siz: 输入长度
             * @return 返回对象实例自身，方便链式操作
             */
            this_t& operator()( const std::vector< uint8_t >& dat, std::size_t siz = 0U )
            {
                opt_t::update( &ctx, (const uint8_t*)&(dat[0]), siz? siz : dat.size() );
                return *this;
            }

            /*********************************************************************
             * @brief 加入多个计算内容
             * @param  b: 输入内容的起始迭代器
             * @param  e: 输入内容的结束迭代器
             * @return 返回对象实例自身，方便链式操作
             */
            template< typename _itr >
            this_t& operator()( _itr b, _itr e )
            {
                for( auto i = b; i != e; ++i )
                {
                    opt_t::update( &ctx, (const uint8_t*)&((*i)[0]), i->size() );
                }

                return *this;
            }

            /*********************************************************************
             * @brief 结果计算并返回结果
             * @param  out: 输出结果
             */
            void result( uint8_t* out )
            {
                opt_t::final( &ctx, out );
            }

            /*********************************************************************
             * @brief 结果计算并返回结果
             * @param  out: 输出结果
             */
            void result( std::vector< uint8_t >& out )
            {
                out.resize( opt_t::emRESULT_SIZE + 1, '\0' );

                opt_t::final( &ctx, &(out[0]) );
            }

            /*********************************************************************
             * @brief 结果计算并返回结果
             * @return 返回字符串结果
             */
            std::vector< uint8_t > result()
            {
                std::vector< uint8_t > ret;

                ret.resize( opt_t::emRESULT_SIZE );

                opt_t::final( &ctx, (uint8_t*)&(ret[0]) );

                return ret;
            }
        };

        /*********************************************************************
         * @brief SHA-1类型别名
         */
        using sha1_t = sha_t< 1 >;

        /*********************************************************************
         * @brief SHA-256类型别名
         */
        using sha256_t = sha_t< 256 >;

    } //namespace safe
} //namespace hude